﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UniRlv.COL;
using UniRlv.Utility;
using UniRlv.Utility.Extend;
using System.Linq;

namespace UniRlv.UI.Main.WarerHourseIn
{
    public partial class FrmCodeInfo : UniRlv.UI.Main.FrmBase
    {
        BindingList<CodeInfo> details = new BindingList<CodeInfo>();
        List<CodeInfo> allInfos = new List<CodeInfo>();

        int total = 0;

        public FrmCodeInfo()
        {
            InitializeComponent();
        }

        private void FrmCodeInfo_Load(object sender, EventArgs e)
        {
            toolBtnQuery.Visible = true;
            toolBtnQuery.Click +=toolBtnQuery_Click;

            lstCodeLevel.SelectedIndex = 0;
            lstQueryType.SelectedIndex = 0;

            toolLstPage.Text = ConfigurationHelper.AppGetString("page");

            UIHelper.InitDataGridView(dgvDetails);
            dgvDetails.DataSource = details;
            dgvDetails.MultiSelect = true;
        }

        private void toolBtnQuery_Click(object sender, EventArgs e)
        {
            lbLineTip.Text = "";

            if (lstQueryType.SelectedIndex == 6)
            {
                details.Clear();
                
                IList<CodeInfo> parr;
                switch (lstCodeLevel.SelectedIndex+1)
                {
                    case 1:
                        parr = PublicObject.arrCode1;
                        lbLineTip.Text = "单通道，扫码数量=" + parr.Count; break;
                    case 2:
                        parr = PublicObject.arrCode2; break;
                    case 3:
                        parr = PublicObject.arrCode3; break;
                    case 4:
                        parr = PublicObject.arrCode4; break;
                    default:
                        parr = PublicObject.arrCode1; break;
                }

                if (lstCodeLevel.SelectedIndex == 0 && PublicObject.arrCode1.bMergeOne)
                {
                    total = PublicObject.arrCode1.Count;
                    lbLineTip.Text = string.Format("通道1扫码数量={0}，通道2扫码数量={1}", PublicObject.arrCode1.GetCount(0), PublicObject.arrCode1.GetCount(1));
                }
                else
                {
                    total = parr.Count;
                }
                

                int pageSize = Convert.ToInt32(toolLstPage.Text);

                if (total > 0)
                {
                    toolTxtPage.Text = "1";
                    toolTxtTip.Text = string.Format("页 共{0}页，{1}条记录", (total - 1) / pageSize + 1, total);

                    toolBtnReload.PerformClick();


                }
                else
                {
                    toolTxtPage.Text = "0";
                    toolTxtTip.Text = string.Format("页 共0页，0条记录");
                }
            }
            else
            {
                string code = txtCode.Text;
                if (!string.IsNullOrEmpty(code))
                {
                    QueryCode(code);
                    txtCode.Text = "";
                }
            }

        }

        public override void OnScanCode(string orgCode, string validCode)
        {
            txtCode.Text = validCode.Trim();
            //lstQueryType.SelectedIndex = 0;
            QueryCode(validCode.Trim());
        }

        private void txtCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (txtCode.Focused && e.KeyCode == Keys.Enter)
            {
                string code = txtCode.Text;
                if (!string.IsNullOrEmpty(code))
                {
                    lbLineTip.Text = "";
                    QueryCode(code);
                    txtCode.Text = "";
                }
            }
        }

        void QueryCode(string code)
        {
            CodeInfo info = CodePrcUtility.FindCode(code);
            CodeInfo parent;
            int total = 0;
            string msg = string.Empty;
            List<CodeInfo> tmpCodes;
            details.Clear();
            allInfos.Clear();

            if (info == null)
            {
                ShowInfoMessageBox("提示", "条码不存在");
                return;
            }

            int idx = CodePrcUtility.FindCodePos(info);
            int idx2 = -1;

            if (PublicObject.bSecond)
            {
                if (info.stationNumber == 2 )
                {
                    idx2 = CodePrcUtility.FindCodePos2(info);
                }
                else if (info.stationNumber == 1)
                {
                    idx2 = CodePrcUtility.FindCodeOnePos2(info, ref msg);
                }
            }

            switch (lstQueryType.SelectedIndex)
            {
                case 0:
                    allInfos.Add(info);
                    break;
                case 1:

                    tmpCodes = CodePrcUtility.FindArrayByPos1(info.stationNumber, idx - 2, 5);
                    foreach (var item in tmpCodes)
                    {
                        allInfos.Add(item);
                    }
                    break;
                case 2:
                    info = CodePrcUtility.GetParent(info, ref msg);

                    if (info == null)
                    {
                        ShowInfoMessageBox("提示", msg);
                    }
                    else
                    {
                        allInfos.Add(info);
                    }

                    break;
                case 3:
                    //同级 + 父码
                    parent = CodePrcUtility.GetParent(info, ref msg);
                    if (parent == null)
                    {
                        ShowInfoMessageBox("提示", msg);
                    }
                    else
                    {
                        tmpCodes = CodePrcUtility.GetLevelSonPackageCodes(parent, ref msg);

                        if (tmpCodes == null)
                        {
                            ShowInfoMessageBox("提示", msg);
                        }
                        else
                        {
                            allInfos.AddRange(tmpCodes);

                            allInfos.Add(parent);
                        }
                    }
                    break;
                case 4:
                    //自身 + 子码
                    tmpCodes = CodePrcUtility.GetLevelSonPackageCodes(info, ref msg);

                    if (tmpCodes == null)
                    {
                        ShowInfoMessageBox("提示", msg);
                    }
                    else
                    {
                        allInfos.AddRange(tmpCodes);

                        allInfos.Add(info);
                    }
                    break;
                case 5://整包装
                    tmpCodes = CodePrcUtility.GetWholePackageCodes(info, ref msg);
                    
                    if (tmpCodes == null)
                    {
                        ShowInfoMessageBox("提示", "查询出错：" + msg);
                    }
                    else
                    {
                        allInfos.AddRange(tmpCodes);

                    }
                    break;
                default:
                    ShowInfoMessageBox("提示", "暂时不支持!");return;

            }

            total = allInfos.Count;
            int pageSize = Convert.ToInt32(toolLstPage.Text);

            if (total > 0)
            {
                toolTxtPage.Text = "1";
                toolTxtTip.Text = string.Format("页 共{0}页，{1}条记录", (total - 1) / pageSize + 1, total);

                toolBtnReload.PerformClick();


            }
            else
            {
                toolTxtPage.Text = "0";
                toolTxtTip.Text = string.Format("页 共0页，0条记录");
            }

            if (idx2>=0)
            {
                if (info.stationNumber == 1)
                {
                    ShowInfoMessageBox("提示", "一级码对应父码已二次采集，本条码的对应二次采集位置：" + (idx2 + 1).ToString());
                }
                else
                {
                    ShowInfoMessageBox("提示", "二级码已二次采集，本条码的对应二次采集位置：" + (idx2 + 1).ToString());
                }
            }
            else
            {
                ShowInfoMessageBox("提示", "本条码一次采集位置：" + (idx + 1).ToString());
            }
            
            
        }

        private void dgvDetails_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDetails.CurrentRow != null)
            {
                CodeInfo code = dgvDetails.CurrentRow.DataBoundItem as CodeInfo;

                txtCode.Text = code.code;
            }
        }

        private void dgvDetails_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvDetails.CurrentRow != null)
            {
                CodeInfo code = dgvDetails.CurrentRow.DataBoundItem as CodeInfo;

                txtCode.Text = code.code;

                lstQueryType.SelectedIndex = 0;

                toolBtnQuery.PerformClick();
            }
        }

        private void lstQueryType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstQueryType.SelectedIndex == 6)
            {
                lstCodeLevel.Visible = true;
                txtCode.ReadOnly = true;

                lstCodeLevel.SelectedIndex = 0;
            }
            else
            {
                lstCodeLevel.Visible = false;
                txtCode.ReadOnly = false;
            }
        }
        #region 分页
        private void toolTxtPage_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int page = Convert.ToInt32(toolTxtPage.Text);

                if (page > 0)
                {
                    toolBtnReload.PerformClick();
                }
            }

        }

        private void toolBtnFirst_Click(object sender, EventArgs e)
        {
            if (total > 0 && toolTxtPage.Text != "1")
            {
                toolTxtPage.Text = "1";
                toolBtnReload.PerformClick();
            }
        }

        private void toolBtnPrevious_Click(object sender, EventArgs e)
        {
            int page = Convert.ToInt32(toolTxtPage.Text);

            if (total > 0 && page > 1)
            {
                toolTxtPage.Text = (page - 1).ToString();
                toolBtnReload.PerformClick();
            }
        }

        private void toolBtnNext_Click(object sender, EventArgs e)
        {
            int pageSize = Convert.ToInt32(toolLstPage.Text);
            int pages = total / pageSize + 1;
            int curPage = Convert.ToInt32(toolTxtPage.Text);

            if (curPage < pages)
            {
                toolTxtPage.Text = (curPage + 1).ToString();
                toolBtnReload.PerformClick();
            }
        }

        private void toolBtnLast_Click(object sender, EventArgs e)
        {
            int pageSize = Convert.ToInt32(toolLstPage.Text);
            int pages = total / pageSize + 1;
            int curPage = Convert.ToInt32(toolTxtPage.Text);

            if (curPage != pages)
            {
                toolTxtPage.Text = pages.ToString();
                toolBtnReload.PerformClick();
            }
        }

        private void toolBtnReload_Click(object sender, EventArgs e)
        {
            Wait();

            int page = Convert.ToInt32(toolTxtPage.Text);
            int pageSize = Convert.ToInt32(toolLstPage.Text);
            string msg = string.Empty;
            List<CodeInfo> li;

            if (lstQueryType.SelectedIndex == 6)
            {
                switch (lstCodeLevel.SelectedIndex + 1)
                {
                    case 1:
                        li = PublicObject.arrCode1.Skip((page-1)*pageSize).Take(pageSize).ToList();
                        total = PublicObject.arrCode1.Count;break;
                    case 2:
                        li = PublicObject.arrCode2.Skip((page-1)*pageSize).Take(pageSize).ToList(); 
                        total = PublicObject.arrCode2.Count;break;
                    case 3:
                        li = PublicObject.arrCode3.Skip((page-1)*pageSize).Take(pageSize).ToList(); 
                        total = PublicObject.arrCode3.Count;break;
                    case 4:
                        li = PublicObject.arrCode4.Skip((page-1)*pageSize).Take(pageSize).ToList(); 
                        total = PublicObject.arrCode4.Count;break;
                    default:
                        li = PublicObject.arrCode1.Skip((page-1)*pageSize).Take(pageSize).ToList(); break;
                }
            }
            else
            {
                li = allInfos.Skip((page - 1) * pageSize).Take(pageSize).ToList();
                total = allInfos.Count;
            }



            details.Clear();
            dgvDetails.Tag = (page - 1) * pageSize;

            if (li != null)
            {
                foreach (var item in li)
                {
                    details.Add(item);
                }

                toolTxtTip.Text = string.Format("页 共{0}页，{1}条记录", (total + pageSize - 1) / pageSize, total);
            }
            else
            {
                toolTxtPage.Text = "0";
                toolTxtTip.Text = string.Format("页 共0页，0条记录");
            }

            WaitBack();
        }

        private void toolLstPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            string msg = string.Empty;

            details.Clear();

            try
            {

                int pageSize = Convert.ToInt32(toolLstPage.Text);
                IList<CodeInfo> parr;
                switch (lstCodeLevel.SelectedIndex + 1)
                {
                    case 1:
                        parr = PublicObject.arrCode1; break;
                    case 2:
                        parr = PublicObject.arrCode2; break;
                    case 3:
                        parr = PublicObject.arrCode3; break;
                    case 4:
                        parr = PublicObject.arrCode4; break;
                    default:
                        parr = PublicObject.arrCode1; break;
                }


                total = parr.Count;

                if (total > 0)
                {
                    toolTxtPage.Text = "1";
                    toolTxtTip.Text = string.Format("页 共{0}页，{1}条记录", (total - 1) / pageSize + 1, total);

                    toolBtnReload.PerformClick();


                }
                else
                {
                    toolTxtPage.Text = "0";
                    toolTxtTip.Text = string.Format("页 共0页，0条记录");
                }

            }
            catch (Exception exp)
            {
                ShowErrorMessageBox(exp);
            }
        }

        #endregion

        private void lstCodeLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            toolBtnQuery.PerformClick();
        }

        private void lstQueryType_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0)
            {
                return;
            }
            e.DrawBackground();
            e.DrawFocusRectangle();
            e.Graphics.DrawString(lstQueryType.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 3);
        }

        private void dgvDetails_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    //若行已是选中状态就不再进行设置
                    if (dgvDetails.Rows[e.RowIndex].Selected == false)
                    {
                        dgvDetails.ClearSelection();
                        dgvDetails.Rows[e.RowIndex].Selected = true;
                    }
                    //只选中一行时设置活动单元格
                    if (dgvDetails.SelectedRows.Count == 1)
                    {
                        dgvDetails.CurrentCell = dgvDetails.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    }
                    //弹出操作菜单
                    contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }

        private void menuDelete_Click(object sender, EventArgs e)
        {
            if (ShowConfirmDialog("请确定", $"确定删除这{dgvDetails.SelectedRows.Count}条记录？") == DialogResult.OK)
            {
                foreach (DataGridViewRow item in dgvDetails.SelectedRows)
                {
                    CodeInfo ci = item.DataBoundItem as CodeInfo;
                    CodePrcUtility.DeleteCode(ci);
                }

                WorkSpace.GetInstance().RefreshCodeQty();
                dgvDetails.ClearSelection();
                toolBtnQuery.PerformClick();
                
            }
        }
    }
}
